﻿import {useEffect, useState} from "react";
import {getWeatherAPI} from "@/api/weather.api.ts";
import {Button} from "@/components/ui/button.tsx";
import {Card} from "@/components/ui/card";
import {Canvas} from "@react-three/fiber";
import WeatherModel from "@/components/WeatherModel";
import sunnyModel from "@/assets/models/sunnyModel.glb";
import yinModel from "@/assets/models/yinModel.glb";
import wind from "@/assets/models/wind.glb";
import {RefreshCcw} from "lucide-react";
import {Slider} from "@/components/ui/slider.tsx";
import {Skeleton} from "@/components/ui/skeleton";

interface WeatherData {
    adcode: string;
    city: string;
    humidity: string;
    humidity_float: string;
    province: string;
    reporttime: string;
    temperature: string;
    temperature_float: string;
    weather: string;
    winddirection: string;
    windpower: string;
}

function Weather() {
    const [weatherData, setWeatherData] = useState<WeatherData | null>(null);
    const [modelPath, setModelPath] = useState(sunnyModel); // 默认晴天模型
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    
    useEffect(() => {
        const fetchWeather = async () => {
            try {
                const response = await getWeatherAPI();
                setWeatherData(response.data.lives[0]);
                updateModel(response.data.lives[0].weather); // 根据天气更新模型
            } catch (error) {
                console.error("Error fetching weather:", error);
                setError("获取天气数据失败，请稍后重试。");
            } finally {
                setLoading(false);
            }
        };
        fetchWeather();
    }, []);
    
    // 根据天气参数更新模型路径
    const updateModel = (weather: string) => {
        switch (weather) {
            case "晴天":
                setModelPath(sunnyModel);
                break;
            case "阴":
                setModelPath(yinModel);
                break;
            case "风":
                setModelPath(wind);
                break;
            default:
                setModelPath(sunnyModel); // 默认晴天模型
        }
    };
    
    const handleRefresh = async () => {
        setLoading(true);
        setError(null);
        try {
            const response = await getWeatherAPI();
            setWeatherData(response.data.lives[0]);
            updateModel(response.data.lives[0].weather);
        } catch (error) {
            console.error("Error fetching weather:", error);
            setError("Failed to fetch weather data. Please try again later.");
        } finally {
            setLoading(false);
        }
    };
    
    if (loading) {
        return (
            <Card
                className="w-[448px] h-[357px] p-6 bg-gradient-to-r  from-themeEnglishLight/60 to-themeEnglishLight/80 dark:from-themeEnglishDark/80 dark:to-themeEnglishDark text-white">
                <Skeleton className="h-8 w-1/2 mb-4"/>
                <Skeleton className="h-12 w-1/4 mb-4"/>
                <Skeleton className="h-4 w-1/3 mb-4"/>
                <Skeleton className="h-4 w-1/2 mb-4"/>
                <Skeleton className="h-4 w-1/2 mb-4"/>
            </Card>
        );
    }
    
    if (error) {
        return (
            <Card
                className="w-[448px] h-[357px] p-6 bg-gradient-to-r from-themeEnglishLight/60 to-themeEnglishLight/80 dark:from-themeEnglishDark/80 dark:to-themeEnglishDark text-white">
                <div className="text-center">
                    <p className="text-red-500 mb-4">{error}</p>
                    <Button onClick={handleRefresh} className="bg-white text-blue-600">
                        <RefreshCcw className="mr-2 h-4 w-4"/>重试
                    </Button>
                </div>
            </Card>
        );
    }
    
    return (
        <Card
            className="w-[448px] h-[357px] p-6 bg-gradient-to-r from-themeEnglishLight/60 to-themeEnglishLight/80 dark:from-themeEnglishDark/80 dark:to-themeEnglishDark text-white"
        >
            <div className="flex justify-between items-start mb-8 relative">
                <div>
                    <h2 className="text-2xl font-bold">{weatherData?.city}</h2>
                    <div className="text-5xl font-light mt-4">{weatherData?.temperature}°C</div>
                    <div className="mt-2">{weatherData?.weather}</div>
                </div>
                <div className="flex flex-col items-center">
                    <Canvas className="w-24 h-24 object-contain mb-2 drop-shadow-lg transition-transform">
                        <WeatherModel modelPath={modelPath}/>
                    </Canvas>
                </div>
                <RefreshCcw onClick={handleRefresh} className="h-4 w-4"/>
            </div>
            <div className="mt-6 space-y-4">
                <div>
                    <div className="flex justify-between mb-2">
                        <span>湿度</span>
                        <span>{weatherData?.humidity}%</span>
                    </div>
                    <Slider
                        value={[parseFloat(weatherData?.humidity || "0")]}
                        max={100}
                        step={1}
                        className="bg-white/20"
                        disabled
                    />
                </div>
                <div>
                    <div className="flex justify-between mb-2">
                        <span>风速</span>
                        <span>{weatherData?.windpower} m/s</span>
                    </div>
                    <Slider
                        value={[parseFloat(weatherData?.windpower || "0")]}
                        max={100}
                        step={1}
                        className="bg-white/20"
                        disabled
                    />
                </div>
            </div>
            <div
                className="text-[18px] relative text-end">{weatherData ? `更新于:${weatherData.reporttime}` : ""}</div>
        </Card>
    );
}

export default Weather;